//
//  GradientLabel.swift
//  CommonTools
//
//  Created by xianquan on 2024/3/7.
//

import Foundation

public class GradientLabel: UIView {
    
    public var text: String? {
        set {
            label.text = newValue
            
//            updateConstraints()
        }
        get {
            label.text
        }
    }

    public var font: UIFont? {
        set {
            label.font = newValue
        }
        get {
            label.font
        }
    }

    public var gradientColors: [UIColor] = [] {
        didSet {
            setupGradient()
            layoutIfNeeded()
        }
    }
    
    private let label = UILabel()
    
    override public init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required public init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        label.frame = bounds
        guard let sublayers = layer.sublayers else {return}
        for l in sublayers {
            if l is CAGradientLayer {
                l.frame = bounds
            }
        }
    }
    
    private func setupGradient(){
        
        if gradientColors.isEmpty {
            return
        }
        
        label.sizeToFit()
        size = label.size
        snp.updateConstraints { make in
            make.width.equalTo(size.width / adapt(1))
            make.height.equalTo(size.height / adapt(1))
        }
        
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = bounds
        gradientLayer.colors = gradientColors.map {$0.cgColor}
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
        layer.insertSublayer(gradientLayer, at: 0)
        addSubview(label)
        gradientLayer.mask = label.layer
    }
}
